package hu.blok1.veilingsite.client.gui;

import java.util.Date;

import hu.blok1.veilingsite.client.Veilingsite;
import hu.blok1.veilingsite.client.data.ProductService;
import hu.blok1.veilingsite.client.data.ProductServiceAsync;
import hu.blok1.veilingsite.shared.Product;
import hu.blok1.veilingsite.shared.User;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.datepicker.client.DateBox;

public class UserCreateProductGUI {
	private VerticalPanel vp;
	private VerticalPanel vpEndDate = new VerticalPanel();
	private VerticalPanel vpPrice = new VerticalPanel();
	private Veilingsite veilingsite;
	private User user;
	private int userID;

	private TextBox createProductNameTextbox = new TextBox();
	private ListBox createProductCategoryListbox = new ListBox();
	private TextBox createProductPrizeTextbox = new TextBox();
	private TextArea createProductDescriptionTextarea = new TextArea();
	private TextBox createProductImageTextbox = new TextBox();
	private Button createProductConfirmButton = new Button();

	private FlexTable createProductForm = new FlexTable();
	private String productName, productDescription, productCategory;
	private int productPrice;
	private String productImageURL;
	
	private DateTimeFormat dtf = DateTimeFormat.getFormat("dd-MM-yyyy HH:mm:ss");

	private DateBox dp = new DateBox();

	private final ProductServiceAsync ProductService = GWT
			.create(ProductService.class);

	public UserCreateProductGUI(VerticalPanel a, Veilingsite vs) {
		veilingsite = vs;
		user = veilingsite.getUser();
		userID = user.getId();

		vp = a;
		vp.clear();
		if (user.isLoggedIn()) {
			vp.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
			vp.add(new Label("Hieronder kunt u een nieuw product toevoegen"));
			vp.add(new Label(" --- "));
			vp.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);

			String[] categoryArray = { "Boeken", "CD's en DVD's", "Games",
					"Elektronica", "Gereedschappen", "Vervoer en onderdelen",
					"Dieren en toebehoren", "Muziekinstrumenten",
					"Sport en fitness", "Diversen" };

			for (int i = 0; i <= 9; i++) {
				createProductCategoryListbox.addItem(categoryArray[i],
						categoryArray[i]);
			}
			cleanTextBoxes();

			createProductDescriptionTextarea.setCharacterWidth(32);
			createProductDescriptionTextarea.setVisibleLines(10);

			createProductNameTextbox.setVisibleLength(40);
			createProductPrizeTextbox.setVisibleLength(40);
			createProductImageTextbox.setVisibleLength(40);

			vpPrice.add(createProductPrizeTextbox);
			vpPrice.add(new Label("Niet gehele prijzen invullen met punt"));

			vpEndDate.add(dp);
			vpEndDate.add(new Label("Gelieve niet langer dan 6 maanden kiezen"));

			createProductConfirmButton.setText("Invoeren");

			createProductForm.setCellSpacing(6);

			createProductForm.setWidget(0, 0, new Label("Naam: "));
			createProductForm.setWidget(1, 0, new Label("Categorie: "));
			createProductForm.setWidget(2, 0, new Label("Prijs: "));
			createProductForm.setWidget(3, 0, new Label("Einddatum: "));
			createProductForm.setWidget(4, 0, new Label("Beschrijving: "));
//			createProductForm.setWidget(5, 0, new Label("URL van image: "));
			createProductForm.setWidget(6, 0, new Label("Product invoeren: "));

			createProductForm.setWidget(0, 1, createProductNameTextbox);
			createProductForm.setWidget(1, 1, createProductCategoryListbox);
			createProductForm.setWidget(2, 1, vpPrice);
			createProductForm.setWidget(3, 1, vpEndDate);
			createProductForm.setWidget(4, 1, createProductDescriptionTextarea);
//			createProductForm.setWidget(5, 1, createProductImageTextbox);
			createProductForm.setWidget(6, 1, createProductConfirmButton);
			
			createProductImageTextbox.setText("a");

			vp.add(createProductForm);

			createProductConfirmButton.addClickHandler(new ClickHandler() {
				
				
				@Override
				public void onClick(ClickEvent event) {
					if (checkValues().equals("")) {
						Product p = new Product(0, productName, productPrice,
								new Date(), dp.getValue(), "",
								productDescription, productImageURL, userID,
								productCategory);
						
						p.setStartDateString(dtf.format(p.getStartDate()));
						p.setEndDateString(dtf.format(p.getEndDate()));
						
						ProductService.createProduct(p,
								new AsyncCallback<Boolean>() {
									@Override
									public void onFailure(Throwable caught) {
										Window.alert("Product aanmaken is mislukt");
									}

									@Override
									public void onSuccess(Boolean result) {
										if (result) {
											Window.alert("Product aanmaken is geslaagd");
											History.newItem("home");
										} else {
											Window.alert("Product aanmaken is alsnog mislukt, onze excuses");
										}
									}
								});
					} else {
						Window.alert(checkValues());
					}
				}
			});
		} else {
			Window.alert("U moet aangemeld zijn om een product aan te maken!");
			History.newItem("login");
		}
	}

	public String checkValues() {
		StringBuilder errorMessage = new StringBuilder();

		productName = createProductNameTextbox.getText();
		productCategory = createProductCategoryListbox
				.getItemText(createProductCategoryListbox.getSelectedIndex());
		productDescription = createProductDescriptionTextarea.getText();

		String prize = createProductPrizeTextbox.getText();
		
		if (prize.equals("") || prize == null) {
			productPrice = 0;
		} else {
			productPrice = Integer.parseInt(prize);
		}

		productImageURL = createProductImageTextbox.getText();

		long sixmonths = (long) 1000.0 * 60 * 60 * 24 * 182;
		Date maxend = new Date(System.currentTimeMillis() + sixmonths);
		
		long fivemin = (long) 1000.0 * 60 * 5;
		Date minstart = new Date(System.currentTimeMillis() + fivemin);

		if (productName.equals(""))
			errorMessage.append("\nGeen product naam ingevuld");
		
		if (!productName.matches("^[A-Za-z0-9-\\s.,\"]{2,50}$"))
			errorMessage.append("\nOngeldige naam ingevuld");
		
		if (productPrice == 0 || productPrice > 999999)
			errorMessage.append("\nOngeldige prijs ingevuld");
		
		if (productDescription.equals(""))
			errorMessage.append("\nGeen product omschrijving ingevuld");
		
		if (!productDescription.matches("^.{2,500}$"))
			errorMessage.append("\nOnjuiste product omschrijving ingevuld");
		
		if (dp.getValue().after(maxend))
			errorMessage.append("\nVeiling eindigt te laat");
		
		if (dp.getValue().before(minstart))
			errorMessage.append("\nVeiling eindigt te vroeg");
		
		return errorMessage.toString();
	}

	public void cleanTextBoxes() {
		dp.setValue(new Date());
		createProductNameTextbox.setText("");
		createProductPrizeTextbox.setText("");
		createProductDescriptionTextarea.setText("");
		createProductImageTextbox.setText("");
	}
}